package com.zhanglinwei.openApiClient.model.request;

import com.zhanglinwei.openApiClient.model.response.OpenApiResponse;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public interface OpenApiRequest<R extends OpenApiResponse> {

    String apiCode();

    default String apiVersion() {
        return "1.0.0";
    }

    default Type responseType() {
        return resolveGenericType();
    }

    default Class<R> responseClass() {
        // 获取当前实例的实际泛型类型
        Type superType = getClass().getGenericSuperclass();
        if (superType instanceof ParameterizedType) {
            ParameterizedType parameterizedType = (ParameterizedType) superType;
            Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
            if (actualTypeArguments.length > 0 && actualTypeArguments[0] instanceof Class) {
                return (Class<R>) actualTypeArguments[0];
            }
        }

        // 获取接口的泛型类型（适用于接口直接实现的情况）
        Type[] genericInterfaces = getClass().getGenericInterfaces();
        for (Type genericInterface : genericInterfaces) {
            if (genericInterface instanceof ParameterizedType) {
                ParameterizedType parameterizedInterface = (ParameterizedType) genericInterface;
                if (parameterizedInterface.getRawType() == OpenApiRequest.class) {
                    Type[] interfaceTypeArgs = parameterizedInterface.getActualTypeArguments();
                    if (interfaceTypeArgs.length > 0 && interfaceTypeArgs[0] instanceof Class) {
                        return (Class<R>) interfaceTypeArgs[0];
                    }
                }
            }
        }

        throw new IllegalStateException("无法确定响应类型，请确保类正确实现了OpenApiRequest接口");
    }

    default Type resolveGenericType() {
        return ((ParameterizedType) getClass()
                .getGenericInterfaces()[0])
                .getActualTypeArguments()[0];
    }

}
